﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using SCSService;
using System.Xml;
using System.Configuration;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using NLog;
using System.Linq.Expressions;
using MvcReCaptcha;
using Recaptcha;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Drawing.Text;
using SCS.Core.Models.ModelsFontend;


namespace SCS.Core.Controllers
{
    public class BaseFontendController : Controller
    {
        private static readonly Logger Logger = LogManager.GetLogger("webatf_test");
        static string olUrl;

        public string DefaultHostGetter() 
        {
            string host=this.Request.Url.Host;
            if (host.Contains("www."))
            {
                host = host.Replace("www.", "");
            }
            return host; 
        }

        public string DefaultPathAndQuerryGetter() { return this.Request.Url.PathAndQuery; }

        public string DefaultUrlRefferer() { return this.Request.UrlReferrer.ToString(); }

        public string DefaultLanguageGetter()
        {
            var arr = this.Request.Url.PathAndQuery.Split('/');

            if (DefaultHostGetter().Contains("localhost"))
            {
                Logger.Info("language local: " + arr[2]);
                return arr[2];
                
            }
            else
            {
                Logger.Info("all url: " + this.Request.Url);
                Logger.Info("url: " + this.Request.Url.PathAndQuery);
                Logger.Info("language live: " + arr[1]);
                if (this.Request.Url.PathAndQuery.Contains("Rejected-By-UrlScan?~"))
                {
                    arr = this.Request.Url.PathAndQuery.Replace("/Rejected-By-UrlScan?~","").Split('/');
                    return arr[1];
                }
                else
                    return arr[1];
                
            }
            
        }

        public int DefaultSiteGuidGetter()
        {
            var arr = this.Request.Url.PathAndQuery.Split('/');

            if (DefaultHostGetter().Contains("localhost"))
            {
                return int.Parse(arr[1]);
            }
            else
            {
                if (Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()) != null)
                {
                    return Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;
                }
                else
                    return 1;
            }

            
        }

        public string DefaultModuleName()
        {
            var arr = this.Request.Url.PathAndQuery.Split('/');

            if (DefaultHostGetter().Contains("localhost"))
            {
                return arr[3];
            }
            else
            {
                return arr[2];
            }

        }

        public string DefaultPageName()
        {
            var arr = this.Request.Url.PathAndQuery.Split('/');

            if (DefaultHostGetter().Contains("localhost"))
            {
                if (arr[4].Contains('?') || arr[4].Contains('&'))
                {
                    string a = arr[4].Substring(0,arr[4].IndexOf('?'));
                    return a;
                }
                else
                    return arr[4];
                
            }
            else
            {
                if (arr[3].Contains('?') || arr[3].Contains('&'))
                {
                    string a = arr[3].Substring(0,arr[3].LastIndexOf('?'));
                    return a;
                }
                else
                    return arr[3];
            }

        }

        public void checkPageView(int siteguid, int pageid,string url404)
        {
            if (!Models.ConfigModel.CheckViewPage(siteguid, pageid))
            {
                Response.Redirect(url404);
            }
        }

        public int GetSiteGuid()
        {
            int siteGuid = 0;
            if (Request.Url.Host == "localhost")
            {
                if (Request.Url.ToString().Contains("favicon.ico"))
                {
                }
                else
                    siteGuid = DefaultSiteGuidGetter();

                Logger.Info("siguid localhost: " + DefaultSiteGuidGetter() + " " + DefaultHostGetter());
            }
            else
            {
                siteGuid = Models.ConfigModel.GetWebsitebyDomain(DefaultHostGetter()).SiteGuid;
                Logger.Info("siteguid live: " + DefaultSiteGuidGetter()+ " "+ DefaultHostGetter() );
            }
                


            return siteGuid;
        }

        public void IntPage()
        {
            if (!Request.Url.ToString().Contains("favicon.ico"))
            {

                int siteGuid = GetSiteGuid();
                Logger.Info("siteGuid live: " + siteGuid);
                int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
                Logger.Info("language live: " + LanguageID);
                int moduleID = Models.ConfigModel.GetModuleIDBySiteGuidAndModuleName(siteGuid, DefaultModuleName());
                int PageID = Models.ConfigModel.GetPageIDByModuleIDAndPageName(moduleID, DefaultPageName());

                checkPageView(siteGuid, PageID, "~/Content/Error/404site.htm");

                SCSService.Config_MasterPage master = Models.ConfigModel.GetMasterPageByPageID(PageID, siteGuid);
                if (master != null)
                {
                    ViewData["MasterPage"] = master.MasterPath != null ? master.MasterPath.ToString() : null;
                }
                else
                {
                    ViewData["MasterPage"] = null;
                }

                var listcontrol = Models.ConfigModel.GetListConfigControlInPage(PageID, siteGuid);
                ViewData["ListControl"] = listcontrol;

                GetHeaderPage();
                //var listArticleStatic = Models.ConfigModel.GetListArticleStaticByListControlID(listcontrol, LanguageID, siteGuid);
                //ViewData["ListArticleStatic"] = listArticleStatic;
            }           
        }

        [ChildActionOnly]
        public ActionResult TopTenProduct()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            

            var query = Models.ModelsFontend.ProductModel.GetListTopTenProduct(LanguageID, siteGuid).AsQueryable();

            var result = query.ToList();

            // Set up our ViewModel
            var viewModel = new TopTenProductViewModels
            {
                ProductItem = result
            };

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/TopTenProduct", viewModel);          

        }

        public List<Product> GetListProductByParam(string param)
        {
            string sortDirection = "DESC";
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
           
            List<SCSService.Type_Product> listType = Models.ModelsFontend.ProductModel.GetListTypeProductByParentIdAndParam(null, LanguageID, GetSiteGuid(), 1, param);

            List<SCSService.Product> listproduct = new List<Product>();
            var type = listType.ToList().FirstOrDefault();
            if (type != null)
            {
                var query = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(type.TypeProductID, LanguageID, siteGuid, 1).AsQueryable();
                var paramsort = Expression.Parameter(typeof(Product), "Product");
                var sortExpression = Expression.Lambda<Func<Product, object>>
                                        (Expression.Convert(Expression.Property(paramsort, "ProductID"), typeof(object)), paramsort);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);

                listproduct = query.ToList();
            }
            

            return listproduct;
        }

        [ChildActionOnly]
        public ActionResult MenuMain()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            
            ViewData["MenuMain"] = GetListMenuBuilder(null);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuMain");

        }       //ex siteGuid 6,7

        [ChildActionOnly]
        public ActionResult SiteMap()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["siteMap"] = siteMapBuilDer(null);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/SiteMap");

        }

        public StringBuilder GetListMenuBuilder(int? id)
        {
            StringBuilder sb = new StringBuilder();            
            return ListMenuBuilder(ref sb, id, GetSiteGuid(),true);
        }

        public StringBuilder ListMenuBuilder(ref StringBuilder sb, int? id, int siteGuid, bool root)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            List<SCSService.Menu> listMenu = Models.ConfigModel.GetListMenuByParent(id, LanguageID, siteGuid,1);
            if (root)
            {
                sb.Append("<ul id='nav'>");
            }
            else
            {
                sb.Append("<ul>");
            }
            foreach (var item in listMenu)
            {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    if (item.MenuUrl.ToLower().Contains("/listarticlesstatic?param"))
                    {
                        string page = item.MenuUrl.Substring(item.MenuUrl.IndexOf("param="));

                        if (item.MenuUrl.ToLower().Contains("/" + DefaultPageName().ToLower()) && Request.Url.PathAndQuery.ToString().ToLower().Contains(page.ToLower()))
                        {
                            sb.Append(" <li class='menuMain active'><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>");
                        }
                        else
                        {
                            sb.Append(" <li class='menuMain'><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>");
                        }
                    }
                    else
                    {
                        if (item.MenuUrl.ToLower().Contains("/" + DefaultPageName().ToLower()))
                        {
                            sb.Append(" <li class='menuMain active'><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>");
                        }
                        else
                        {
                            sb.Append(" <li class='menuMain'><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>");
                        }
                    }
                    
                }
                else
                {
                    if (item.MenuUrl.ToLower().Contains("/listarticlesstatic?param"))
                    {
                        string page = item.MenuUrl.Substring(item.MenuUrl.IndexOf("param="));

                        if (item.MenuUrl.Contains("/" + DefaultPageName()) && Request.Url.PathAndQuery.ToString().ToLower().Contains(page.ToLower()))
                        {
                            sb.Append("<li class='menuMain active'><a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>");
                        }
                        else
                        {
                            sb.Append("<li class='menuMain'><a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>");
                        }
                    }
                    else
                    {
                        if (item.MenuUrl.Contains("/" + DefaultPageName()))
                        {
                            sb.Append("<li class='menuMain active'><a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>");
                        }
                        else
                        {
                            sb.Append("<li class='menuMain'><a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>");
                        }
                    }
                    
                }

                List<SCSService.Menu> listChild = Models.ConfigModel.GetListMenuByParent(item.MenuId, LanguageID, siteGuid,1);
                if (listChild.Count() > 0)
                {
                    ListMenuBuilder(ref sb, item.MenuId, siteGuid,false);
                }
                sb.Append("</li> ");
            }
            sb.Append("</ul>");

            return sb;
        }

        public void GetHeaderPage()
        { 
            int moduleID = Models.ConfigModel.GetModuleIDBySiteGuidAndModuleName(GetSiteGuid(), DefaultModuleName());
            int PageID = Models.ConfigModel.GetPageIDByModuleIDAndPageName(moduleID, DefaultPageName());
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            string url=Request.Url.PathAndQuery;
            string re = "";
            if (DefaultHostGetter() == "localhost")
            {
                string[] urls = url.Split('/');
                for (int i = 0; i < urls.Count(); i++)
                { 
                    if(i!=0 && i!=1 && i!=2)
                    {
                        re += "/" + urls[i];
                    }
                    
                }
            }
            else
            {
                string[] urls = url.Split('/');
                for (int i = 0; i < urls.Count(); i++)
                {
                    if (i != 0 && i!=1)
                    {
                        re += "/" + urls[i];
                    }

                }
            }

            int? MenuId=Models.ConfigModel.GetMenuBySiteGuidAndLanguageIDAndUrl(LanguageID,GetSiteGuid(),re)!=null?Models.ConfigModel.GetMenuBySiteGuidAndLanguageIDAndUrl(LanguageID,GetSiteGuid(),re).MenuId:0;
            string param=Request.QueryString["param"];

            Config_Metadata metadata = Models.ConfigModel.GetMetadata(PageID, MenuId, param, GetSiteGuid(), LanguageID);

            //Get header default
            string title = "";
            string keyword = "";
            string description = "";
            string PoweredBy = "";
            string dcCreator = "";
            string Author = "";
            string robots = "";
            string language = "";
            string created = "";
            string modified = "";
            string revisitAfter = "";
            string datePublichcation = "";
            string homePage = "";

            if (metadata != null)
            {
                title = metadata.MetaTitle != null ? metadata.MetaTitle : "";
                keyword = metadata.MetaKeywords != null ? metadata.MetaKeywords : "";
                description = metadata.MetaDescription != null ? metadata.MetaDescription : "";
                PoweredBy = metadata.MetaPoweredBy != null ? metadata.MetaPoweredBy : "";
                dcCreator = metadata.MetaDcCreator != null ? metadata.MetaDcCreator : "";
                Author = metadata.MetaAuthor != null ? metadata.MetaAuthor : "";
                robots = metadata.MetaRobots != null ? metadata.MetaRobots : "";
                language = metadata.DcLanguage != null ? metadata.DcLanguage : "";
                created = metadata.MetaDctermsCreated != null ? metadata.MetaDctermsCreated.ToString() : "";
                modified = metadata.MetaDcctermsModified != null ? metadata.MetaDcctermsModified.ToString() : "";
                revisitAfter = metadata.RevisitAfter != null ? metadata.RevisitAfter : "";
                datePublichcation = metadata.DatePublication != null ? metadata.DatePublication : "";
                homePage = metadata.Homepage != null ? metadata.Homepage : "";
            }
             


            string[] arr;

            int[] arrDetail=new int[]{12,26,33,43,40};

            if (arrDetail.Contains(PageID))
            { 
                // Cac page detail (product,article,article static,...)
                //if (DefaultHostGetter() == "localhost")
                //{
                    arr = Request.Url.ToString().Split('/');
                    if (arr.Length > 7)
                    {
                        if (arr[7] != null && arr[7] != string.Empty)
                        {
                            int objID = int.Parse(arr[7].ToString());
                            var obj = Models.ModelsFontend.ProductModel.GetProductByID(objID);
                            if (obj != null)
                            {
                                title = obj.Title != null ? obj.Title : title;
                                description = obj.MetaDescription != null ? obj.MetaDescription : description;
                                keyword = obj.MetaKeyword != null ? obj.MetaKeyword : keyword;
                            }
                        }
                    }
                   
                //}
                //else
                //{
                //    arr = Request.Url.ToString().Split('/');
                //    if (arr[4] != null && arr[4] != string.Empty)
                //    {
                //        int objID = int.Parse(arr[4].ToString());
                //        var obj = Models.ModelsFontend.ProductModel.GetProductByID(objID);
                //        if (obj != null)
                //        {
                //            title = obj.Title != null ? obj.Title : title;
                //            description = obj.MetaDescription != null ? obj.MetaDescription : description;
                //            keyword = obj.MetaKeyword != null ? obj.MetaKeyword : keyword;
                //        }
                //    }
                //}
                
            }

            ViewData["title"] = title;
            ViewData["keyword"] = keyword;
            ViewData["description"] = description;
            ViewData["PoweredBy"] = PoweredBy;
            ViewData["dcCreator"] = dcCreator;
            ViewData["Author"] = Author;
            ViewData["robots"] = robots;
            ViewData["language"] = language;
            ViewData["created"] = created;
            ViewData["modified"] = modified;
            ViewData["revisitAfter"] = revisitAfter;
            ViewData["datePublichcation"] = datePublichcation;
            ViewData["homePage"] = homePage;

        }

        public List<SCSService.Menu> siteMapBuilDer(int? id)
        {
            List<SCSService.Menu> sb = new List<SCSService.Menu>();
            return siteMapBuilder(ref sb, id, GetSiteGuid(), true);
        }

        public List<SCSService.Menu> siteMapBuilder(ref List<SCSService.Menu> sb, int? id, int siteGuid, bool root)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            List<SCSService.Menu> listMenu = Models.ConfigModel.GetListMenuByParent(id, LanguageID, siteGuid, 1);
            
            foreach (var item in listMenu)
            {
                if (!root)
                {
                    if (DefaultHostGetter().Contains("localhost"))
                    {
                        if (item.MenuUrl.ToLower().Contains("/listarticlesstatic?param"))
                        {
                            string page = item.MenuUrl.Substring(item.MenuUrl.IndexOf("param="));

                            if (item.MenuUrl.ToLower().Contains("/" + DefaultPageName().ToLower()) && Request.Url.PathAndQuery.ToString().ToLower().Contains(page.ToLower()))
                            {

                                item.MenuText = "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuUrl + "'>" + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuText + "</a>" + "#" + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";

                                Menu me = Models.ConfigModel.GetMenuByID(id);
                                foreach (var itemStr in sb)
                                {
                                    if (itemStr.MenuId == me.MenuId)
                                    {
                                        if (itemStr.MenuText.Contains("#"))
                                        {
                                            int laststr = itemStr.MenuText.LastIndexOf("#") + 1;
                                            string addStr = itemStr.MenuText.Substring(0, laststr);
                                            item.MenuText = addStr + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                                        }
                                    }
                                }
                            }
                            else
                            {

                                item.MenuText = "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuUrl + "'>" + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuText + "</a>" + "#" + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";

                                Menu me = Models.ConfigModel.GetMenuByID(id);
                                foreach (var itemStr in sb)
                                {
                                    if (itemStr.MenuId == me.MenuId)
                                    {
                                        if (itemStr.MenuText.Contains("#"))
                                        {
                                            int laststr = itemStr.MenuText.LastIndexOf("#") + 1;
                                            string addStr = itemStr.MenuText.Substring(0, laststr);
                                            item.MenuText = addStr + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (item.MenuUrl.ToLower().Contains("/" + DefaultPageName().ToLower()))
                            {

                                item.MenuText = "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuUrl + "'>" + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuText + "</a>" + "#" + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";

                                Menu me = Models.ConfigModel.GetMenuByID(id);
                                foreach (var itemStr in sb)
                                {
                                    if (itemStr.MenuId == me.MenuId)
                                    {
                                        if (itemStr.MenuText.Contains("#"))
                                        {
                                            int laststr = itemStr.MenuText.LastIndexOf("#") + 1;
                                            string addStr = itemStr.MenuText.Substring(0, laststr);
                                            item.MenuText = addStr + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                                        }
                                    }
                                }
                            }
                            else
                            {

                                item.MenuText = "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuUrl + "'>" + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuText + "</a>" + "#" + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";

                                Menu me = Models.ConfigModel.GetMenuByID(id);
                                foreach (var itemStr in sb)
                                {
                                    if (itemStr.MenuId == me.MenuId)
                                    {
                                        if (itemStr.MenuText.Contains("#"))
                                        {
                                            int laststr = itemStr.MenuText.LastIndexOf("#") + 1;
                                            string addStr = itemStr.MenuText.Substring(0, laststr);
                                            item.MenuText = addStr + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                                        }
                                    }
                                }
                            }
                        }

                    }
                    else
                    {
                        if (item.MenuUrl.ToLower().Contains("/listarticlesstatic?param"))
                        {
                            string page = item.MenuUrl.Substring(item.MenuUrl.IndexOf("param="));

                            if (item.MenuUrl.Contains("/" + DefaultPageName()) && Request.Url.PathAndQuery.ToString().ToLower().Contains(page.ToLower()))
                            {

                                item.MenuText = "<a href='/" + DefaultLanguageGetter() + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuUrl + "'>" + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuText + "</a>" + "#" + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";

                                Menu me = Models.ConfigModel.GetMenuByID(id);
                                foreach (var itemStr in sb)
                                {
                                    if (itemStr.MenuId == me.MenuId)
                                    {
                                        if (itemStr.MenuText.Contains("#"))
                                        {
                                            int laststr = itemStr.MenuText.LastIndexOf("#") + 1;
                                            string addStr = itemStr.MenuText.Substring(0, laststr);
                                            item.MenuText = addStr + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                                        }
                                    }
                                }
                            }
                            else
                            {

                                item.MenuText = "<a href='/" + DefaultLanguageGetter() + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuUrl + "'>" + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuText + "</a>" + "#" + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";

                                Menu me = Models.ConfigModel.GetMenuByID(id);
                                foreach (var itemStr in sb)
                                {
                                    if (itemStr.MenuId == me.MenuId)
                                    {
                                        if (itemStr.MenuText.Contains("#"))
                                        {
                                            int laststr = itemStr.MenuText.LastIndexOf("#") + 1;
                                            string addStr = itemStr.MenuText.Substring(0, laststr);
                                            item.MenuText = addStr + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (item.MenuUrl.Contains("/" + DefaultPageName()))
                            {

                                item.MenuText = "<a href='/" + DefaultLanguageGetter() + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuUrl + "'>" + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuText + "</a>" + "#" + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";

                                Menu me = Models.ConfigModel.GetMenuByID(id);
                                foreach (var itemStr in sb)
                                {
                                    if (itemStr.MenuId == me.MenuId)
                                    {
                                        if (itemStr.MenuText.Contains("#"))
                                        {
                                            int laststr = itemStr.MenuText.LastIndexOf("#") + 1;
                                            string addStr = itemStr.MenuText.Substring(0, laststr);
                                            item.MenuText = addStr + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                                        }
                                    }
                                }
                            }
                            else
                            {

                                item.MenuText = "<a href='/" + DefaultLanguageGetter() + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuUrl + "'>" + Models.ConfigModel.GetMenuByID(item.PartnerMenuId).MenuText + "</a>" + "#" + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";

                                Menu me = Models.ConfigModel.GetMenuByID(id);
                                foreach (var itemStr in sb)
                                {
                                    if (itemStr.MenuId == me.MenuId)
                                    {
                                        if (itemStr.MenuText.Contains("#"))
                                        {
                                            int laststr = itemStr.MenuText.LastIndexOf("#") + 1;
                                            string addStr = itemStr.MenuText.Substring(0, laststr);
                                            item.MenuText = addStr + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                                        }
                                    }
                                }
                            }
                        }

                    }


                }
                else
                {
                    if (DefaultHostGetter().Contains("localhost"))
                    {
                        if (item.MenuUrl.ToLower().Contains("/home/index"))
                        {
                            item.MenuText = "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "' class='breadcrumbHome'>" + item.MenuText + "</a>";
                        }
                        else
                        {
                            item.MenuText = "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Home/Index" + "' class='breadcrumbHome'>" + Models.ConfigModel.GetMenuBySiteGuidAndLanguageIDAndUrl(LanguageID, siteGuid, "/Home/Index").MenuText + "</a>" + "#" + "<a href='/" + siteGuid + "/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                        }
                        
                    }
                    else
                    {
                        if (item.MenuUrl.ToLower().Contains("/home/index"))
                        {
                            item.MenuText = "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "' class='breadcrumbHome'>" + item.MenuText + "</a>";
                        }
                        else
                        {
                            item.MenuText = "<a href='/" + DefaultLanguageGetter() + "/Home/Index" + "' class='breadcrumbHome'>" + Models.ConfigModel.GetMenuBySiteGuidAndLanguageIDAndUrl(LanguageID, siteGuid, "/Home/Index").MenuText + "</a>" + "#" + "<a href='/" + DefaultLanguageGetter() + item.MenuUrl + "'>" + item.MenuText + "</a>";
                        }
                        
                    }
                }


                sb.Add(item);
                List<SCSService.Menu> listChild = Models.ConfigModel.GetListMenuByParent(item.MenuId, LanguageID, siteGuid,1);
                if (listChild.Count() > 0)
                {
                    siteMapBuilder(ref sb, item.MenuId, siteGuid, false);
                }

            }

            return sb;
        }

      

        public StringBuilder GetListArticleCategoryBuilderRecursive(int? id, bool recursive,int? level)
        {
            StringBuilder sb = new StringBuilder();
            return GetListArticleCategoryBuilderRecursive(ref sb, id, recursive,true,level); // Not recusive =false
        }

        public StringBuilder GetListArticleCategoryBuilderRecursive(ref StringBuilder sb, int? id, bool? recursive, bool root,int? level)
        {
            int siteGuid = GetSiteGuid();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            List<SCSService.Article_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleCategoryByParentIdAndLevel(level,id, LanguageID, GetSiteGuid(), true);
            if (root)
            {
                sb.Append("<ul id='category-menu'>");
            }
            else
            {
                sb.Append("<ul class='subcategory'>");
            }
            foreach (var item in listCate)
            {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    if (item.CategoriesUrl == null)
                    {
                        //Article Not Url 
                        sb.Append("<li id='menuSlive" + item.CategoriesID + "'><a class='menuSliveA' href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Article/ListArticles/" + item.CategoriesID + "'>" + item.CategoriesName + "</a>");
                    }
                    else
                    {
                        //Article have Url
                        sb.Append("<li id='menuSlive" + item.CategoriesID + "'><a class='menuSliveA' href='" + item.CategoriesUrl + "'>" + item.CategoriesName + "</a>");
                    }
                }
                else
                {
                    if (item.CategoriesUrl == null)
                    {
                        //Article not Url
                        sb.Append("<li id='menuSlive" + item.CategoriesID + "'><a class='menuSliveA' href='/" + DefaultLanguageGetter() + "/Article/ListArticles/" + item.CategoriesID + "'>" + item.CategoriesName + "</a>");
                    }
                    else
                    {
                        //Article have Url
                        sb.Append("<li id='menuSlive" + item.CategoriesID + "'><a class='menuSliveA' href='" + item.CategoriesUrl + "'>" + item.CategoriesName + "</a>");
                    }
                }

                List<SCSService.Article_Category> listChild = Models.ModelsFontend.ArticaleModel.GetListArticleCategoryByParentId(item.CategoriesID, LanguageID, GetSiteGuid(), true);
                if (listChild.Count() > 0 && recursive == true)
                {
                    GetListArticleCategoryBuilderRecursive(ref sb, item.CategoriesID, recursive,false,level);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");


            return sb;
        }

        [ChildActionOnly]
        public ActionResult MenuArticleNotRecursive()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramSliveShowByParamMain");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["SliveShowByParamMain"] = listStatic;
            }

            ViewData["MenuArticleNotRecursive"] = GetListArticleCategoryBuilderRecursive(null, false,null);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleNotRecursive");

        }       //ex siteGuid 6

        /// <summary>
        /// Lấy menu Article từ level 2 và có đệ quy 
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        public ActionResult MenuArticleFromLevelSecond(int? id)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            //Get Menu Article From Level 2 and Recursive
            ViewData["MenuArticleFromLevelSecond"] = GetListArticleCategoryBuilderRecursive(id, true,-2);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleFromLevelSecond");

        }   //ex siteGuid 6

        [ChildActionOnly]
        public ActionResult MenuArticleFromLevelSecondNotRecursive(int? id)
        {
            string pageName = DefaultPageName();
            string[] arr;
            int idParent=0;
            if (pageName.ToLower() != "ListArticles".ToLower())
            { 
                //khong phai trang list article (trang detail)
                string urlOld = Request.UrlReferrer!=null?Request.UrlReferrer.ToString():"";
                if (urlOld != "" && urlOld.Contains('/'))
                {
                    arr = urlOld.Split('/');
                    idParent = int.Parse(arr[arr.Length - 1]);

                }                
            }
            if (idParent != 0)
            {
                id = idParent;
            }
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            //Get Menu Article From Level 2 and Recursive
            //ViewData["MenuArticleFromLevelSecondNotRecursive"] = GetListArticleCategoryBuilderRecursive(id, false,-1);
            int test= Models.ModelsFontend.ArticaleModel.CheckLevelArticleCategory(id, LanguageID, siteGuid, true);
            if (Models.ModelsFontend.ArticaleModel.CheckLevelArticleCategory(id, LanguageID, siteGuid, true) > 0)
            {
                //level lon hon 0 la level con cua menu 
                //Lay menu với id là parent của chính nó
                if (id != null)
                {
                    var art = Models.ModelsFontend.ArticaleModel.GetArticleCategory((int)id);
                    List<SCSService.Article_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleCategoryByParentIdAndLevel(-1, art.CategoriesParentID, LanguageID, GetSiteGuid(), true);
                    ViewData["MenuArticleFromLevelSecondNotRecursive"] = listCate;
                }
                else
                { 
                    return PartialView("~/Content/Error/404site.htm");
                }

            }
            else
            {
                List<SCSService.Article_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleCategoryByParentIdAndLevel(-1, id, LanguageID, GetSiteGuid(), true);
                ViewData["MenuArticleFromLevelSecondNotRecursive"] = listCate;
            }
            
            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleFromLevelSecondNotRecursive");

        }   //ex siteGuid 6

        [ChildActionOnly]
        public ActionResult BannerListArticleStatic(int? id)
        {
            string pageName = DefaultPageName();
            string[] arr;
            int idParent = 0;
            if (pageName.ToLower() == "ArticleStaticDetail".ToLower())
            {
                //khong phai trang list article (trang detail)
                string urlOld = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";
                if (urlOld != "" && urlOld.Contains("/ListArticlesStatic"))
                {
                    arr = urlOld.Split('/');
                    idParent = int.Parse(arr[arr.Length - 1]);

                }
                else
                {
                    var artStaticFrontpage = Models.ModelsFontend.ArticaleModel.GetListArticleStaticFrontpageByArticleStaticID(id??0);
                    idParent = artStaticFrontpage.FirstOrDefault().StaticCategoryID;
                }

                if (idParent != 0)
                {
                    id = idParent;
                }
            }
            else if (pageName.ToLower() == "ListArticlesStatic".ToLower())
            {
                //trang list
                if (id == null)
                    id = 0;
            }
            else
            {
                if (id != null)
                {
                    var list = Models.ModelsFontend.ArticaleModel.GetListArticleStaticFrontpageByArticleStaticID((int)id);
                    if (list != null && list.Count() > 0)
                    {
                        id = list.FirstOrDefault().StaticCategoryID;
                    }
                }
                if (id == null)
                {
                    int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
                    int siteGuid = GetSiteGuid();
                    string param = LoadNodeConfigSite(siteGuid, "paramMenuArticleStaticCategoryIntroduction");
                    string paramTypeMenuCategoryIntro = LoadNodeConfigSite(siteGuid, "paramTypeMenuCategoryIntroduction");

                    List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

                    if (paramTypeMenuCategoryIntro != string.Empty && paramTypeMenuCategoryIntro != null)
                    {
                        if (paramTypeMenuCategoryIntro == "only")
                        {
                            var cate = listCate.ToList().FirstOrDefault();
                            if (cate != null)
                            {
                                id = cate.StaticCategoryID; 
                            }
                            
                        }
                        else if (paramTypeMenuCategoryIntro == "multi")
                        {
                            
                        }
                    }
                }
            }

            
            // Set up our ViewModel
            var viewModel = new ListArticleStaticViewModels
            {
                //ArticleStaticItem = result,
                ArticleStaticCategory = id != null ? Models.ModelsFontend.ArticaleModel.GetArticleStaticCategory((int)id) : null
            };


            return PartialView("../BaseFontend/" + GetSiteGuid() + "/BannerListArticleStatic", viewModel);

        }   //ex siteGuid 6

        [ChildActionOnly]
        public ActionResult BannerListArticle(int? id)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            string pageName = DefaultPageName();
            string[] arr;
            int idParent = 0;
            if (pageName.ToLower() == "ArticleDetail".ToLower())
            {
                //khong phai trang list article (trang detail)
                string urlOld = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";
                if (urlOld != "" && urlOld.Contains("/ListArticles"))
                {
                    arr = urlOld.Split('/');
                    idParent = int.Parse(arr[arr.Length - 1]);
                }

                if (idParent != 0)
                {
                    id = idParent;
                }
            }
            else if (pageName.ToLower() == "ListArticles".ToLower())
            { 
                //trang list
                if (id == null)
                    id = 0;
            }
            else
            {
                if (id != null)
                {
                    var list = Models.ModelsFontend.ArticaleModel.GetListArticleFrontpageByArticleID((int)id);
                    if (list != null && list.Count() > 0)
                    {
                        id = list.FirstOrDefault().CategoriesID;
                    }
                }

            }

            
            // Set up our ViewModel
            var viewModel = new ListArticleViewModels
            {
                //ArticleItem = result,
                ArticleCategory = id != null ? Models.ArticaleMasterModel.GetArticleCategory((int)id) : null
            };

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/BannerListArticle", viewModel);

        }   //ex siteGuid 6

        [ChildActionOnly]
        public ActionResult SliveBottom()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramSliveShowByParam");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["SliveShowByParam"] = listStatic;
            }

            //sliveLogo là Article Static trong Article Static Category có param = "SliveLogo"
            //EX: siteGuid 6


           
            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/SliveBottom");

        }   //ex siteGuid 6

        [ChildActionOnly]
        public ActionResult BannerTop()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramBannerTop");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
            }

            int id = 0;
            if (listStatic.Count > 0)
            {
                id = listStatic.FirstOrDefault().StaticID;
            }

            //Contact là Article Static trong Article Static Category có param = "BannerTop"
            //EX: siteGuid 7


            var art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/BannerTop", art);

        }       //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult MenuBottom()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramMenuBottom");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
            }

            int id = 0;
            if (listStatic.Count > 0)
            {
                id = listStatic.FirstOrDefault().StaticID;
            }

            //Contact là Article Static trong Article Static Category có param = "BannerTop"
            //EX: siteGuid 7


            var art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuBottom", art);

        }       //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult BannerBottom()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramBannerBottom");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
            }

            int id = 0;
            if (listStatic.Count > 0)
            {
                id = listStatic.FirstOrDefault().StaticID;
            }

            //Contact là Article Static trong Article Static Category có param = "BannerBottom"
            //EX: siteGuid 7


            var art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/BannerBottom", art);

        }       //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult MenuTypeProduct()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["MenuTypeProduct"] = GetListTypeProductBuilder(null);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuTypeProduct");

        }       //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult MenuArticleCategory(int? id)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            //Get Menu Article From Level 2 and Recursive
            ViewData["MenuArticleCategory"] = GetListArticleCategoryBuilderRecursive(id, true, null);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleCategory");

        }

        [ChildActionOnly]
        public ActionResult MenuArticleStaticCategoryWithParam()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramMenuTabArticleStaticCategory");
            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            ViewData["MenuArticleStaticCategoryWithParam"] = listCate;

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleStaticCategoryWithParam");

        }

        [ChildActionOnly]
        public ActionResult MenuArticleStaticCategoryByParam(int? id,string param)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            //Get Menu Article From Level 2 and Recursive
            ViewData["MenuArticleCategory"] = GetListArticleStaticCategoryBuilder(null,param);

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuArticleStaticCategoryByParam");

        }

        public StringBuilder GetListArticleStaticCategoryBuilder(int? id,string param)
        {
            StringBuilder sb = new StringBuilder();
            return ListArticleStaticCategoryBuilder(ref sb,true, id,param);
        }

        public StringBuilder ListArticleStaticCategoryBuilder(ref StringBuilder sb,bool root, int? id, string param)
        {
            int siteGuid = GetSiteGuid();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(id, LanguageID, GetSiteGuid(), true,param);
            if (root)
            {
                sb.Append("<ul class='menu' id='mainlevel'>");
            }
            else
            {
                sb.Append("<ul class='submenu'>");
            }
            foreach (var item in listCate)
            {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    if (root)
                    {
                        if (param != null && param != string.Empty)
                        {
                            sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Article/ListArticlesStatic/" + item.StaticCategoryID + "?param="+param+"' class='parent' id='menu"+item.StaticCategoryID+"'>" + item.StaticCategoryName + "</a><span></span>");
                        }
                        else
                        {
                            sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Article/ListArticlesStatic/" + item.StaticCategoryID + "' class='parent' id='menu" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a><span></span>");
                        }
                        
                    }
                    else
                    {
                        if (param != null && param != string.Empty)
                        {
                            sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Article/ListArticlesStatic/" + item.StaticCategoryID + "?param=" + param + "' id='menu" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a>");
                        }
                        else
                        {
                            sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Article/ListArticlesStatic/" + item.StaticCategoryID + "' id='menu" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a>");
                        }
                        
                    }
                    
                }
                else
                {
                    if (root)
                    {
                        if (param != null && param != string.Empty)
                        {
                            sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Article/ListArticlesStatic/" + item.StaticCategoryID + "?param=" + param + "' class='parent' id='menu" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a><span></span>");
                        }
                        else
                        {
                            sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Article/ListArticlesStatic/" + item.StaticCategoryID + "' class='parent' id='menu" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a><span></span>");
                        }
                        
                    }
                    else
                    {
                        if (param != null && param != string.Empty)
                        {
                            sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Article/ListArticlesStatic/" + item.StaticCategoryID + "?param=" + param + "' id='menu" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a>");
                        }
                        else
                        {
                            sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Article/ListArticlesStatic/" + item.StaticCategoryID + "' id='menu" + item.StaticCategoryID + "'>" + item.StaticCategoryName + "</a>");
                        }
                        
                    }
                    
                }

                List<SCSService.Artilce_Static_Category> listChild = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(item.StaticCategoryID, LanguageID, GetSiteGuid(), true,param);
                if (listChild.Count() > 0)
                {
                    ListArticleStaticCategoryBuilder(ref sb,false, item.StaticCategoryID,param);
                }
                if (root)
                {
                    sb.Append("</li><span></span>");
                }
                else
                {
                    sb.Append("</li>"); 
                }
                
            }
            sb.Append("</ul>");

            return sb;
        }


        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListProductNew()
        {
            ViewData["typeList"] = "grid";
            //string param = LoadNodeConfigSite(GetSiteGuid(), "paramListProductNew");
            //int numberProductNew = int.Parse(LoadNodeConfigSite(GetSiteGuid(), "paramNumberListProductNew"));

            ///return ket qua la 1 childAction tai 1 folder khac
           // return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProductNew", GetListProductByParam(param).Take(numberProductNew));
            return ListProductNew("grid");
        }               //ex siteGuid 7

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListProductNew(string typeList)
        {
            var url = Request.Url.PathAndQuery;
            if (Request.QueryString["typeList"] != null)
            {
                typeList = Request.QueryString["typeList"].ToString();
            }

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            string param = LoadNodeConfigSite(GetSiteGuid(), "paramListProductNew");
            int numberProductNew = int.Parse(LoadNodeConfigSite(GetSiteGuid(), "paramNumberListProductNew"));
             var cart = ShoppingCart.GetCart(this.HttpContext);
            var list = cart.GetListCartItemByCartID();
            ShoppingCart shopcart = new ShoppingCart();

            ViewData["cart"] = list;

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProductNew", GetListProductByParam(param).Take(numberProductNew));

        }       //ex siteGuid 7


        

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListProductHot()
        {
            ViewData["typeList"] = "list";
            return ListProductHot("list");            
        }   //ex siteGuid 7

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListProductHot(string typeList)
        {
            var url = Request.Url.PathAndQuery;
            if (Request.QueryString["typeList"] != null)
            {
                typeList = Request.QueryString["typeList"].ToString();
            }


            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            string param = LoadNodeConfigSite(GetSiteGuid(), "paramListProductHot");
            int numberProductNew = int.Parse(LoadNodeConfigSite(GetSiteGuid(), "paramNumberListProductHot"));
            var cart = ShoppingCart.GetCart(this.HttpContext);
            var list = cart.GetListCartItemByCartID();
            ShoppingCart shopcart = new ShoppingCart();

            ViewData["cart"] = list;
            //return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProductHot", GetListProductByParam(param).Take(numberProductNew));

        }   //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult CartMini()
        {
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = Models.ModelsFontend.ShoppingCart.GetCart(this.HttpContext);
            long totalCountCard = 0; 
            long number = 0;
            var list = cart.GetListCartItemByCartID();
            foreach(var ite in list)
            {
                number = ite.Count.Value;
                totalCountCard += number;
            }
            // Set up our ViewModel
            var viewModel = new ShoppingCartViewModels
            {
                CartItems = cart.GetListCartItemByCartID(),
                //CartTotal = totalCountCard
                CartTotal = cart.GetTotalValueCartItem(languageId),
                CartTotalcount=totalCountCard
     
            };

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/CartMini", viewModel);
        }       //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult CartTiny()
        {
            int? languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var cart = Models.ModelsFontend.ShoppingCart.GetCart(this.HttpContext);

            // Set up our ViewModel
            var viewModel = new ShoppingCartViewModels
            {
                CartItems = cart.GetListCartItemByCartID(),
                CartTotal = cart.GetTotalValueCartItem(languageId)
            };

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/CartTiny", viewModel);
        }       //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult SliveLarge()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramSliveLarge");
            int numberSilveLarger = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberSliveLarge"));

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["SliveLarge"] = listStatic;
                ViewData["numberSilveLarger"] = numberSilveLarger;
            }
            else
            {
                ViewData["SliveLarge"] = null;
                ViewData["numberSilveLarger"] = 0;
            }

            //sliveLogo là Article Static trong Article Static Category có param = "SliveLarge"
            //EX: siteGuid 7

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/SliveLarge");

        }       //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult SliveRight()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramSliveRight");
            int numberSliveRight = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberSliveRight"));

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["SliveRight"] = listStatic;
                ViewData["numberSliveRight"] = numberSliveRight;
            }
            else
            {
                ViewData["SliveRight"] = null;
                ViewData["numberSliveRight"] = 0;
            }

            //sliveLogo là Article Static trong Article Static Category có param = "SliveRight"
            //EX: siteGuid 7

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/SliveRight");

        }       //ex siteGuid 7

        [ChildActionOnly]
        public ActionResult ColumAds()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramColumAds");
            int numberSilveLarger = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberColumAds"));

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["ColumAds"] = listStatic;
                ViewData["NumberColumAds"] = numberSilveLarger;
            }
            else
            {
                ViewData["ColumAds"] = null;
                ViewData["NumberColumAds"] = 0;
            }

            //sliveLogo là Article Static trong Article Static Category có param = "ColumAds"
            //EX: siteGuid 8

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/ColumAds");

        }       //ex siteGuid 8

        public ActionResult Scroll()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramScroll");
            int numberSilveLarger = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberScroll"));

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["Scroll"] = listStatic;
                ViewData["NumberScroll"] = numberSilveLarger;
            }
            else
            {
                ViewData["Scroll"] = null;
                ViewData["NumberScroll"] = 0;
            }

            //Scroll là Article Static trong Article Static Category có param = "Scroll"
            //EX: siteGuid 8

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/Scroll");

        }       //ex siteGuid 7

        public StringBuilder GetListTypeProductBuilder(int? id)
        {
            StringBuilder sb = new StringBuilder();
            int siteGuid = GetSiteGuid();

            return ListTypeProductBuilder(ref sb, id, siteGuid,true);
        }

        public StringBuilder ListTypeProductBuilder(ref StringBuilder sb, int? id, int siteGuid, bool root)
        {
            //List Type Product with Param is Null

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            List<SCSService.Type_Product> listType = Models.ModelsFontend.ProductModel.GetListTypeProductByParentId(id, LanguageID, siteGuid,1);
            
            if (root)
            {
                sb.Append("<ul id='category-menu'>");
            }
            else
            {
                sb.Append("<ul class='subcategory'>");
            }
            foreach (var item in listType)
            {
                if (DefaultHostGetter().Contains("localhost"))
                {
                    sb.Append("<li id='menuSlive" + item.TypeProductID + "'><a class='menuSliveA' href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Product/ListProduct/" + item.TypeProductID + "'>" + item.TypeProductName + "</a>"); 
                }
                else
                {
                    sb.Append("<li id='menuSlive" + item.TypeProductID + "'><a class='menuSliveA' href='/" + DefaultLanguageGetter() + "/Product/ListProduct/" + item.TypeProductID + "'>" + item.TypeProductName + "</a>");
                }

                List<SCSService.Type_Product> listChild = Models.ModelsFontend.ProductModel.GetListTypeProductByParentId(item.TypeProductID, LanguageID, siteGuid,1);
                if (listChild.Count() > 0)
                {
                    ListTypeProductBuilder(ref sb, item.TypeProductID,siteGuid, false);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public StringBuilder GetListArticleStaticCategoryBuilderRecursive(int? id, bool recursive,string param)
        {
            StringBuilder sb = new StringBuilder();
            return GetListArticleStaticCategoryBuilderRecursive(ref sb, id, recursive, true,param); // Not recusive =false
        }

        public StringBuilder GetListArticleStaticCategoryBuilderRecursive(ref StringBuilder sb, int? id, bool? recursive, bool root,string param)
        {
            int siteGuid = GetSiteGuid();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(id, LanguageID, GetSiteGuid(), true,param);
            if (root)
            {
                sb.Append("<ul id='menuArticleCate'>");
            }
            else
            {
                sb.Append("<ul>");
            }
            foreach (var item in listCate)
            {

                if (DefaultHostGetter().Contains("localhost"))
                {
                    //Article Not Url 
                    sb.Append("<li id='menuArticleCate" + item.StaticCategoryID + "'><a class='menuArticleCateA' href=''>" + item.StaticCategoryName + "</a></li>");
                }
                else
                {
                    //Article not Url
                    sb.Append("<li id='menuArticleCate" + item.StaticCategoryID + "'><a class='menuSliveA' href=''>" + item.StaticCategoryName + "</a></li>");
                }

                List<SCSService.Artilce_Static_Category> listChild = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(item.StaticCategoryID, LanguageID, GetSiteGuid(), true,param);
                if (listChild.Count() > 0 && recursive == true)
                {
                    GetListArticleStaticCategoryBuilderRecursive(ref sb, item.StaticCategoryID, recursive, false,param);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        protected string LoadNodeConfigSite(int siteguid,string nodeKey)
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath("~") + "\\Content\\WebsiteTheme\\" + siteguid + "\\Web.config");
            XmlNode node = xmldoc.SelectSingleNode("configuration/appSettings/add[@key = '"+nodeKey+"']");
            if (node != null)
            {
                XmlNode valueAttribute = node.Attributes.GetNamedItem("value");
                if (valueAttribute != null)
                {
                    //txtTime.Text = (int.Parse(valueAttribute.Value.ToString()) / 60000).ToString();
                    return valueAttribute.Value.ToString();
                }
                else
                    return "";
            }
            else
                return "";
        }

        public bool CheckKeyConfigSite(int siteguid,string Keys)
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath("~") + "\\Content\\WebsiteTheme\\" + "\\" + siteguid + "\\Web.config");
            XmlNode node = xmldoc.SelectSingleNode("configuration/appSettings/add[@key = '" + Keys + "']");
            //XmlNode valueAttribute = node.Attributes.GetNamedItem("value");
            // save file config
            if (node != null)
            {
                return true;
            }
            else
                return false;
        }

        public void Update(int siteguid,string Values, string Keys)
        {
            //update the config file
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(Server.MapPath("~") + "\\Content\\WebsiteTheme\\" + "\\" + siteguid + "\\Web.config");
            XmlNode node = xmldoc.SelectSingleNode("configuration/appSettings/add[@key = '" + Keys + "']");
            XmlNode valueAttribute = node.Attributes.GetNamedItem("value");
            // save file config
            if (valueAttribute != null)
            {
                valueAttribute.InnerXml = Values;
                xmldoc.Save(Server.MapPath("~") + "\\Content\\WebsiteTheme\\" + siteguid + "\\Web.config");
            }

            //update the cached setting
            //System.Configuration.ConfigurationManager.AppSettings.Set("" + Keys + "", Values);
            //LoadGridView(int.Parse(dropRows.SelectedValue));
        }

        public void CreateNode(int siteguid, string Values, string Keys)
        {

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(ConfigurationManager.AppSettings["Path"] + "\\" + siteguid + "\\Web.config");
            XmlNode appSettingNode = xmldoc.SelectSingleNode("configuration/appSettings");

            //Create a new node
            XmlElement newkey = xmldoc.CreateElement("add");
            newkey.SetAttribute("key", Keys);
            newkey.SetAttribute("value", Values);

            appSettingNode.AppendChild(newkey);

            xmldoc.Save(ConfigurationManager.AppSettings["Path"] + "\\" + siteguid + "\\Web.config");
            //LoadGridView(int.Parse(dropRows.SelectedValue));
        }

        public void UpdatePagerViewData(int totalPages, int totalRows, int currentPage, int pageSize,string param)
        {
            ViewData["pagerStats"] = GenPagerStats(totalRows, currentPage, pageSize);
            ViewData["totalPageDrop"] = GenPageDrop(totalPages, currentPage);

            if (totalPages == 1)
            {
                ViewData["isPagerVisible"] = false;
                return;
            }

            int lastPage = totalPages;

            ViewData["isPagerVisible"] = true;
            ViewData["currentPage"] = currentPage;
            ViewData["totalPages"] = totalPages;
            ViewData["param"] = param;


            if (currentPage == 1)
            {
                ViewData["isFirstPage"] = true;
            }
            else
            {
                ViewData["isFirstPage"] = false;
                ViewData["previousPage"] = currentPage - 1;
            }


            if (currentPage == lastPage)
            {
                ViewData["isLastPage"] = true;
            }
            else
            {
                ViewData["isLastPage"] = false;

                ViewData["nextPage"] = currentPage + 1;
                ViewData["lastPage"] = lastPage;
            }
        }

        public void UpdateSorterViewData(string sortField, string sortDirection)
        {
            ViewData["sortField"] = sortField;
            ViewData["sortDirection"] = sortDirection;
        }

        public static string GenPagerStats(int totalRows, int currentPage, int pageSize)
        {
            int firstRow = (currentPage - 1) * pageSize + 1;
            int lastRow = Math.Min(firstRow + pageSize - 1, totalRows);

            string stats;
            if (firstRow == lastRow)
                stats = "Row " + firstRow + " of " + totalRows;
            else
                stats = "Rows " + firstRow + "-" + lastRow + " of " + totalRows;

            return stats;
        }

        public static SelectList GenPageDrop(int totalPage, int currentPage)
        {

            var tp = new List<string> { };
            for (int i = 1; i < (totalPage + 1); i++)
            {
                tp.Add("" + i);
            }
            return new SelectList(tp, currentPage);
        }

        public static SelectList PageSizeSelectList()
        {
            var pageSizes = new List<string> { "5", "10", "20", "40" };
            return new SelectList(pageSizes, "Value");
        }

        public List<Type_Product> GetListTypeProductDropBasic(string name, int? status, int? order, string param, int? id, int LanguagesID, int siteGuid)
        {
            List<Type_Product> sb = new List<Type_Product>();
            return ListTypeProductDropBasic(name, status, order, param, ref sb, id, true, LanguagesID, siteGuid);
        }

        public List<Type_Product> ListTypeProductDropBasic(string name, int? status, int? order, string param, ref List<Type_Product> sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Type_Product> listType = Models.StockModel.GetListTypeProductByParentIDSearch(name, status, order, param, id, LanguagesID, siteGuid);

            foreach (var item in listType)
            {
                if (!root)
                {
                    item.TypeProductName = Models.StockModel.GetTypeProduct((int)item.ParentTypeProductID).TypeProductName + ">>" + item.TypeProductName;

                    Type_Product pa = Models.StockModel.GetTypeProduct((int)id);
                    foreach (var itemStr in sb)
                    {
                        if (itemStr.TypeProductID == pa.TypeProductID)
                        {
                            if (itemStr.TypeProductName.Contains(">>"))
                            {
                                int laststr = itemStr.TypeProductName.LastIndexOf(">>") + 2;
                                string addStr = itemStr.TypeProductName.Substring(0, laststr);
                                item.TypeProductName = addStr + item.TypeProductName;
                            }
                        }
                    }

                }


                sb.Add(item);
                List<SCSService.Type_Product> listChild = Models.StockModel.GetListTypeProductByParentIDSearch(name, status, order, param, item.TypeProductID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListTypeProductDropBasic(name, status, order, param, ref sb, item.TypeProductID, false, LanguagesID, siteGuid);
                }

            }

            return sb;
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult SignIns()
        {
            ViewData["LoginFalse"] = false;
            var Login = new Models.CollectionFontend.LoginCollection();

            return PartialView("../BaseFontend/" + GetSiteGuid() + "/SignIns", Login);
        }       //ex siteGuid 8

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult SignIns(FormCollection values)
        {
            string olUrl = Request.UrlReferrer.AbsoluteUri;
            string redirectStr = "";
            var Login = new Models.CollectionFontend.LoginCollection();
            TryUpdateModel(Login);

            if ((Login.UserName == null && Login.Password == null) || Login.UserName==null ||Login.Password==null)
            {
                redirectStr = olUrl;
                ViewData["redirectStr"] = redirectStr;
                ViewData["LoginFalse"] = false;
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/SignIns", Login);
            }

            try
            {
                int idLogin = Models.ModelsFontend.UserWebModel.LoginUser(Login.UserName, Login.Password) != null ? Models.ModelsFontend.UserWebModel.LoginUser(Login.UserName, Login.Password).UserID : 0;
                if (idLogin > 0)
                {
                    if (Login.Remember)
                    {
                        HttpCookie ck = new HttpCookie("Sercurity_Uesr_Name");
                        ck.Value = Login.UserName;
                        ck.Expires = DateTime.Now.AddMonths(1);//Thoi han luu cookie
                        HttpContext.Response.Cookies.Add(ck);

                        HttpCookie ckPass = new HttpCookie("Sercurity_Uesr_Password");
                        ck.Value = Login.Password;
                        ck.Expires = DateTime.Now.AddMonths(1);//Thoi han luu cookie
                        HttpContext.Response.Cookies.Add(ckPass);
                    }

                    //Check website login for user
                    List<System_Website> listSite = Models.ModelsFontend.UserWebModel.GetListWebsiteByUserCustomer(idLogin);

                    if ((listSite.Count() == 0))
                    {

                    }
                    else
                    {
                        //int count = 0;
                        bool check = false;
                        foreach (var item in listSite)
                        {
                            if (DefaultHostGetter().Contains("localhost"))
                            {
                                if (item.SiteGuid == DefaultSiteGuidGetter())
                                {
                                    check = true;
                                }
                            }
                            else
                            {
                                if (item.domain == DefaultHostGetter())
                                {
                                    check = true;
                                }
                            }

                        }
                        if (check)
                        {
                            Session["UserID"] = idLogin;
                            Session["LogInSite"] = DefaultSiteGuidGetter();     //Ghi lai website khach hang da dang nhap
                            //Doi voi User co Permission cao nhat la 3 thi chi duoc login tren site da dang ky

                            //Ghi lại log SignIn
                            SCSService.Security_User_Log log = new Security_User_Log();
                            log.UserID = idLogin;
                            log.LoginDate = DateTime.Now;
                            log.LogDetail = "SignIn website :" + DefaultSiteGuidGetter();

                            Session["LogID"] = Models.ModelsFontend.UserWebModel.CreateLog(log);

                            if (DefaultHostGetter().Contains("localhost"))
                            {
                                if (Session["NextAction"] != null)
                                {
                                    redirectStr = Session["NextAction"].ToString();
                                }
                                else
                                    redirectStr = "/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Home/Index";

                                //return Redirect(Session["NextAction"] != null ? Session["NextAction"].ToString() : "/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Home/Index");
                            }
                            else
                            {
                                if (Session["NextAction"] != null)
                                {
                                    redirectStr = Session["NextAction"].ToString();
                                }
                                else
                                    redirectStr = "/" + DefaultLanguageGetter() + "/Home/Index";
                                //return Redirect(Session["NextAction"] != null ? Session["NextAction"].ToString() : "/" + DefaultLanguageGetter() + "/Home/Index");
                            }

                        }

                    }
                }
                else
                {
                    Session["UserID"] = null;
                    Session["LogInSite"] = null;
                    //if (DefaultHostGetter().Contains("localhost"))
                    //{
                    //    redirectStr = "/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                    //}
                    //else {
                    //    redirectStr = "/" + DefaultLanguageGetter() + "/UserWeb/SignIn";
                    //}
                    ViewData["LoginFalse"] = false;
                    return PartialView("../BaseFontend/" + GetSiteGuid() + "/SignIns", Login);
                }

            }
            catch
            {
                ViewData["LoginFalse"] = false;
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/SignIns", Login);
            }

            ViewData["redirectStr"] = redirectStr;
            ViewData["LoginFalse"] = true;
            //return PartialView("../BaseFontend/" + GetSiteGuid() + "/SignIns", Login);
            return PartialView("../Commont/ResultSignIn");
        }       //ex siteGuid 8

        public ActionResult SignInVL()
        {
            string redirectStr = "";
            Session["UserID"] = 60;                             // ID khách hàng vãng lai
            Session["LogInSite"] = DefaultSiteGuidGetter();     //Ghi lai website khach hang da dang nhap

            //Ghi lại log SignIn
            SCSService.Security_User_Log log = new Security_User_Log();
            log.UserID = 60;                                    // ID khách hàng vãng lai
            log.LoginDate = DateTime.Now;
            log.LogDetail = "SignIn website :" + DefaultSiteGuidGetter();

            Session["LogID"] = Models.ModelsFontend.UserWebModel.CreateLog(log);

            if (DefaultHostGetter().Contains("localhost"))
            {

                    redirectStr  = "/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrder";
            }
            else
            {
                    redirectStr = "/" + DefaultLanguageGetter() + "/Checkout/PaymentOrder";
              
            }

            return Redirect(redirectStr);

            //ViewData["redirectStr"] = redirectStr;
            //return PartialView("../Commont/ResultSignIn");
        }

        public ActionResult LogOut()
        {
            olUrl = Request.UrlReferrer.AbsoluteUri;
            Session["UserID"] = null;
            Session["LogInSite"] = null;
            string redirectStr="";
            if (DefaultHostGetter().Contains("localhost"))
            {
               
                    redirectStr = "/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/Home/Index";

            }
            else
            {
                
                    redirectStr = "/" + DefaultLanguageGetter() + "/Home/Index";

            }
            return Redirect(redirectStr);
        }       //ex siteGuid 8

        [ChildActionOnly]
        public ActionResult BoxContact()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramContact");

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
            }

            //ViewData["ContactArticleStaticCategory"] = listStatic.FirstOrDefault();
            int id = 0;
            if (listStatic.Count > 0)
            {
                id = listStatic.FirstOrDefault().StaticID;
            }

            //BoxContact là Article Static trong Article Static Category có param = "Contact"
            //EX: siteGuid 9


            var art = Models.ModelsFontend.ArticaleModel.GetArticleStaticByID((int)id);
            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/BoxContact", art);

        }  //ex siteGuid 9

        [ChildActionOnly]
        public ActionResult BoxCLB()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramBoxCLB");
            int numberSilveLarger = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberBoxCLB"));

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["BoxCLB"] = listStatic;
                ViewData["numberBoxCLB"] = numberSilveLarger;
                ViewData["BoxCategory"] = cate;
            }
            else
            {
                ViewData["BoxCLB"] = null;
                ViewData["numberBoxCLB"] = 0;
                ViewData["BoxCategory"] = null;
            }

            //BoxCLB là Article Static trong Article Static Category có param = "BoxCLB"
            //EX: siteGuid 9

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/BoxCLB");

        }       //ex siteGuid 9

        [ChildActionOnly]
        public ActionResult BoxNotice()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramBoxNotice");
            int numberSilveLarger = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberBoxNotice"));

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["BoxNotice"] = listStatic;
                ViewData["numberBoxNotice"] = numberSilveLarger;
                ViewData["BoxCategory"] = cate;
            }
            else
            {
                ViewData["BoxNotice"] = null;
                ViewData["numberBoxNotice"] = 0;
                ViewData["BoxCategory"] = null;
            }

            //BoxCLB là Article Static trong Article Static Category có param = "BoxNotice"
            //EX: siteGuid 9

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/BoxNotice");

        }       //ex siteGuid 9

        [ChildActionOnly]
        public ActionResult BoxAlbum()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramBoxAlbum");
            int numberSilveLarger = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberBoxAlbum"));

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["BoxAlbum"] = listStatic;
                ViewData["numberBoxAlbum"] = numberSilveLarger;
                ViewData["BoxCategory"] = cate;
            }
            else
            {
                ViewData["BoxAlbum"] = null;
                ViewData["numberBoxAlbum"] = 0;
                ViewData["BoxCategory"] = null;
            }

            //BoxCLB là Article Static trong Article Static Category có param = "BoxAlbum"
            //EX: siteGuid 9

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/BoxAlbum");

        }       //ex siteGuid 9

        [ChildActionOnly]
        public ActionResult Announcements()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            string param = LoadNodeConfigSite(siteGuid, "paramAnnouncements");
            int numberSilveLarger = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberAnnouncements"));

            List<SCSService.Artilce_Static_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticleStaticCategoryByParentIdAndParam(null, LanguageID, GetSiteGuid(), true, param);

            List<SCSService.Article_Static> listStatic = new List<Article_Static>();
            var cate = listCate.ToList().FirstOrDefault();
            if (cate != null)
            {
                listStatic = Models.ModelsFontend.ArticaleModel.GetListArticleStaticByCategory(cate.StaticCategoryID, LanguageID, siteGuid, true);
                ViewData["Announcements"] = listStatic;
                ViewData["numberAnnouncements"] = numberSilveLarger;
                ViewData["BoxCategory"] = cate;
            }
            else
            {
                ViewData["Announcements"] = null;
                ViewData["numberAnnouncements"] = 0;
                ViewData["BoxCategory"] = null;
            }

            //BoxCLB là Article Static trong Article Static Category có param = "Announcements"
            //EX: siteGuid 9

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/Announcements");

        }       //ex siteGuid 9


        [ChildActionOnly]
        public ActionResult ContactOnline()
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            int number = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberNickSupprot"));

            List<SCSService.Support> listSupport = Models.ModelsFontend.SupportModel.GetListSupport(LanguageID, GetSiteGuid()).Take(number).ToList();

            if (listSupport != null && listSupport.Count>0)
            {
                ViewData["listSupport"] = listSupport;
                ViewData["NumberNick"] = number;
            }
            else
            {
                ViewData["listSupport"] = null;
                ViewData["NumberNick"] = 0;
            }

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/ContactOnline");

        }       //ex siteGuid 8
        
         public ActionResult CaptchaImage(string prefix, bool noisy = true)
        {
            var rand = new Random((int)DateTime.Now.Ticks);
            //generate new question
            int a = rand.Next(10, 99);
            int b = rand.Next(0, 9);
            var captcha = string.Format("{0} + {1} = ?", a, b);

            //store answer
            Session["Captcha" + prefix] = a + b;

            //image stream
            FileContentResult img = null;

            using (var mem = new MemoryStream())
            using (var bmp = new Bitmap(130, 30))
            using (var gfx = Graphics.FromImage((Image)bmp))
            {
                gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                //add noise
                if (noisy)
                {
                    int i, r, x, y;
                    var pen = new Pen(Color.Yellow);
                    for (i = 1; i < 10; i++)
                    {
                        pen.Color = Color.FromArgb(
                        (rand.Next(0, 255)),
                        (rand.Next(0, 255)),
                        (rand.Next(0, 255)));

                        r = rand.Next(0, (130 / 3));
                        x = rand.Next(0, 130);
                        y = rand.Next(0, 30);

                        gfx.DrawEllipse(pen,x-r,y-r,r,r);

                    }
                }

                //add question
                gfx.DrawString(captcha, new Font("Tahoma", 15), Brushes.Gray, 2, 3);

                //render as Jpeg
                bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);
                img = this.File(mem.GetBuffer(), "image/Jpeg");
            }

            return img;
        }

         [ChildActionOnly]
         public ActionResult CountdownTimer()
         {
             int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
             int siteGuid = GetSiteGuid();

             ///return ket qua la 1 childAction tai 1 folder khac
             return PartialView("../BaseFontend/" + siteGuid + "/CountdownTimer");

         }

         [ChildActionOnly]
         public ActionResult Top5News()
         {
             int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
             int siteGuid = GetSiteGuid();
             string param = LoadNodeConfigSite(siteGuid, "paramTop5News");
             int numberTop5News = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberTop5News"));

             List<SCSService.Article_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticaleCategoryBySiteGuidAndLanguageIDAndParam(LanguageID, GetSiteGuid(),param);

             List<SCSService.Article> list = new List<Article>();
             var cate = listCate.ToList().FirstOrDefault();
             if (cate != null)
             {
                 list = Models.ModelsFontend.ArticaleModel.GetListArticleByCategory(cate.CategoriesID, LanguageID, siteGuid).OrderByDescending(p => p.ArticleID).ToList();
                 ViewData["Top5News"] = list;
                 ViewData["numberparamTop5News"] = numberTop5News;
             }
             else
             {
                 ViewData["Top5News"] = null;
                 ViewData["numberparamTop5News"] = 0;
             }

             //sliveLogo là Article Static trong Article Static Category có param = "SliveLarge"
             //EX: siteGuid 7

             ///return ket qua la 1 childAction tai 1 folder khac
             return PartialView("../BaseFontend/" + siteGuid + "/Top5News");

         }       //ex siteGuid 7


         [ChildActionOnly]
         public ActionResult Top5Support()
         {
             int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
             int siteGuid = GetSiteGuid();
             string param = LoadNodeConfigSite(siteGuid, "paramTop5Support");
             int numberTop5Support = int.Parse(LoadNodeConfigSite(siteGuid, "paramNumberTop5Support"));

             List<SCSService.Article_Category> listCate = Models.ModelsFontend.ArticaleModel.GetListArticaleCategoryBySiteGuidAndLanguageIDAndParam(LanguageID, GetSiteGuid(), param);

             List<SCSService.Article> list = new List<Article>();
             var cate = listCate.ToList().FirstOrDefault();
             if (cate != null)
             {
                 list = Models.ModelsFontend.ArticaleModel.GetListArticleByCategory(cate.CategoriesID, LanguageID, siteGuid).OrderByDescending(p=>p.ArticleID).ToList();
                 ViewData["Top5Support"] = list;
                 ViewData["numberparamTop5Support"] = numberTop5Support;
             }
             else
             {
                 ViewData["Top5News"] = null;
                 ViewData["numberparamTop5Support"] = 0;
             }

             ///return ket qua la 1 childAction tai 1 folder khac
             return PartialView("../BaseFontend/" + siteGuid + "/Top5Support");

         }       //ex siteGuid 7

         [ChildActionOnly]
         [AcceptVerbs(HttpVerbs.Get)]
         public ActionResult ContactSendEmail(string result)
         {

             var email = new Models.CollectionFontend.ContactSendEmailCollection();
             if (result != null && result != string.Empty)
             {
                 ViewData["result"] = result;
             }
             else
             {
                 ViewData["result"] = null;
             }
             return PartialView("../Commont/WebShop/ContactSendEmail", email);

         }

         [ChildActionOnly]
         [AcceptVerbs(HttpVerbs.Post)]
         public ActionResult ContactSendEmail(FormCollection collection)
         {

             var email = new Models.CollectionFontend.ContactSendEmailCollection();
             TryUpdateModel(email);

             if (Session["Captcha"] == null || Session["Captcha"].ToString() != email.Captcha)
             {
                 ModelState.AddModelError("Captcha", "Kết quả sai.Xin vui lòng thử lại.");
                 ViewData["Result"] = "Xin vui lòng nhập kết quả.";
                 email.re = "Xin vui lòng nhập kết quả.";
                 return PartialView("../Commont/WebShop/ContactSendEmail", email);
             }
             else
             {
                 int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
                 int siteGuid = GetSiteGuid();
                 string paramEmailReceive = LoadNodeConfigSite(siteGuid, "paramAddressEmailReceiveComment");
                 SCSService.BaseService baseSvc = new BaseService();
                 baseSvc.SendMailMessage(paramEmailReceive, email.Subject, email.Content, email.Name, email.Company, email.Address, email.Phone, email.Email);
                 ViewData["Result"] = "Bạn đã gửi thành công!";
                 email.re = "Bạn đã gửi thành công!";
             }

             return PartialView("../Commont/WebShop/ContactSendEmail", email);


         }
    }
}
